<?php

namespace app\api\controller;

use app\admin\model\service\Service;
use app\admin\model\Technician;
use app\common\controller\Frontend;
use ba\PayLib;
use think\facade\Db;
use think\facade\Log;
use Yansongda\Pay\Pay;

class OrderAddClock extends Frontend
{
    // protected array $noNeedLogin = ['*'];

    protected array $noNeedPermission = ['*'];

    /**
     * 创建订单
     */
    public function create(): void
    {
        $params = $this->request->post();
        Log::info('加钟订单创建参数', $params);

        $order_id = $params['order_id'];
        $service_num = $params['service_num'] ?? 1; #加钟数量
        $service_id = $params['service_id'] ?? 0;

        $serviceInfo = Service::where('service_id', $service_id)->field('service_id,service_name,service_price,service_duration')->findOrEmpty();
        if (empty($serviceInfo)) {
            $this->error('服务项目不存在');
        }
        #加钟价格
        $service_price = bcmul($serviceInfo->service_price, $service_num, 2);

        $orderInfo = \app\api\model\Order::where('id', $order_id)->find();
        if (!$orderInfo) {
            $this->error('订单不存在');
        }

        $addClockOrderState = \app\api\model\Order::where('association_order_sn', $orderInfo->order_sn)->value('order_state');
        Log::info('加钟订单状态' . $addClockOrderState);

        #订单必须在进行中 而且 加钟时间不能和技师预约时间冲突
        if ($orderInfo->order_state != 'Start' || $this->isTimeConflict($orderInfo, $service_num)) {
            Log::info('订单状态为服务中才能加钟或技师时间已被预约');
            $this->error('技师时间已被预约');
        }

        $orderModel = new \app\api\model\Order();
        #加钟开始时间
        $service_start_time = date("Y-m-d H:i:s", $this->serviceEndTime($orderInfo));

        $order_sn = 'JZ' . date("YmdHis", time()) . time() . rand(1000, 9999);
        $save = [];
        $save['service_id'] = $service_id;
        $save['user_id'] = $this->auth->id;
        $save['service_start_time'] = $service_start_time;
        $save['service_price'] = $serviceInfo->service_price;
        $save['service_num'] = $service_num;
        $save['service_duration'] = $serviceInfo->service_duration;
        $save['service_total_price'] = $service_price;
        $save['order_sn'] = $order_sn;
        $save['create_time'] = date("Y-m-d H:i:s", time());
        $save['order_state'] = 'ToBePaid';
        $save['technician_id'] = $orderInfo->technician_id;
        $save['address_username'] = $orderInfo->address_username;
        $save['address_tel'] = $orderInfo->address_tel;
        $save['address_lng'] = $orderInfo->address_lng;
        $save['address_lat'] = $orderInfo->address_lat;
        $save['address_house'] = $orderInfo->address_house;
        $save['address_content'] = $orderInfo->address_content;
        $save['technician_address'] = $orderInfo->technician_address;
        $save['technician_tel'] = $orderInfo->technician_tel;
        $save['remarks'] = "";
        $save['type'] = 2;
        $save['association_order_sn'] = $orderInfo->order_sn;
        $save['area_id'] = $orderInfo->area_id;

        $create = $orderModel->create($save);


        if (!$create) {
            $this->error("加钟订单创建失败");
        }

        if (isset($params['pay_type']) && $params['pay_type'] == 'balance') {
            $this->success("订单创建成功", ['order_sn' => $order_sn]);
        } else {
            #微信支付 JSApi支付
            $order = [
                'out_trade_no' => $order_sn,
                'description' => $serviceInfo->service_name,
                'amount' => [
                    'total' => $service_price * 100, //分
                ],
                'payer' => [
                    'openid' => $this->openid(),
                ],
                'attach' => 'orderPayCallback'   #扩展信息
            ];
            $result = Pay::wechat(PayLib::getConfig())->mp($order);
            Log::info('创建订单 支付返回信息' . json_encode($result));
            $this->success("订单创建成功", ['order_sn' => $order_sn, 'pay_url' => $result]);
        }
    }


    /**
     * #计算订单结束时间
     * @return float|int
     */
    protected function serviceEndTime($orderInfo): float|int
    {
        return strtotime($orderInfo->service_start_time) + ($orderInfo->service_duration * $orderInfo->service_num * 60);
    }


    /**
     * 获取加钟规则
     * @return void
     */
    public function getAddClockRule(): void
    {
        $this->success('success', [
            'service_duration' => get_sys_config('ageing') * 60,
            'service_price' => get_sys_config('add_clock_price')
        ]);
    }

    /**
     * 计算价格
     * @return void
     */
    public function getCountPrice(): void
    {
        $price = $this->request->param('price') ?? 0;
        $num = $this->request->param('num') ?? 0;

        $price = bcmul($price, $num, 2);
        $ba_coupon = $this->request->param("coupon_id") ?? 0;
        if ($ba_coupon) {
            $coupon = Db::table("ba_coupon")
                ->where([
                    'coupon_id' => $ba_coupon
                ])
                ->find();
            $price = bcsub($price, $coupon['price'], 2);
        }

        $param = $this->request->param();

        $lng = $param['lng'] ?? null;
        $lat = $param['lat'] ?? null;
        $t_id = $param['t_id'] ?? null;
        $area_id = $param['area_id'] ?? null;

        if (empty($lng)) {
            $this->success('', [
                'res' => $price
            ]);
        }

        $info = Technician::where('technician_id', $t_id)->field('technician_id,lng,lat,is_travel')->find();

        if ($info->is_travel == 1) {
            $this->success('', [
                'res' => $price
            ]);
        }

        $km = distance($info->lat, $info->lng, $lat, $lng);
        $fare_price = fare_total($area_id, $km);
        $price_total = bcadd($price, $fare_price, 2);

        $this->success('', [
            'res' => $price_total
        ]);
    }


}